package it.eng.area118.mdocommon.android.notification;

import it.eng.area118.mdocommon.Notification;
import it.eng.area118.mdocommon.android.log.BasicLogger;
import it.eng.area118.mdocommon.android.model.AndroidModelContainer;
import it.eng.area118.mdocommon.android.util.AndroidApplicationContext;
import it.eng.area118.mdocommon.android.util.StringUtils;
import it.eng.area118.mdocommon.notification.DialogCallback;
import it.eng.area118.mdocommon.notification.InputDateDialogCallback;
import it.eng.area118.mdocommon.notification.InputTextDialogCallback;
import it.eng.area118.mdocommon.notification.SimpleAlertNotificationCallback;
import it.eng.area118.mdocommon.notification.YesNoAlertNotificationCallback;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.text.InputFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class AndroidNotification implements Notification {

	public final static String TAG = AndroidNotification.class.getSimpleName();

	private static final int HELLO_ID = 1;

	@Override
	public <E> E showStatusBarNotification(String uiKey, int icon,
			String sTickerText, String contentTitle, String contentText) {
		BasicLogger.writeLog(TAG, "statusBarNotification");
		Activity activity = (Activity) AndroidApplicationContext.getInstance()
				.getApplicationContextValue(uiKey);
		String ns = Context.NOTIFICATION_SERVICE;

		NotificationManager mNotificationManager = (NotificationManager) activity
				.getSystemService(ns);
		// int icon = R.drawable.notification_icon;
		CharSequence tickerText = sTickerText;
		long when = System.currentTimeMillis();

		android.app.Notification notification = new android.app.Notification(
				icon, tickerText, when);

		Context context = activity.getApplicationContext();
		// CharSequence contentTitle = "My notification";
		// CharSequence contentText = "Hello World!";
		// Intent notificationIntent = new Intent(this, MyClass.class);
		// PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
		// notificationIntent, 0);

		notification.setLatestEventInfo(context, contentTitle, contentText,
				null);

		mNotificationManager.notify(HELLO_ID, notification);
		return (E) notification;

	}

	@Override
	public AlertDialog showYesNoAlert(String title, String msg,
			final YesNoAlertNotificationCallback callback) {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				AndroidApplicationContext.getInstance().getApplicationContext());
		builder.setTitle(title);
		builder.setMessage(msg).setCancelable(false)
				.setPositiveButton("Si", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						if (callback != null) {
							callback.onYes();

						}
					}
				})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						if (callback != null) {
							callback.onNo();
						}

					}
				});

		// AlertDialog alert = builder.create();
		return builder.show();

	}

	@Override
	public AlertDialog showSimpleAlert(final String title, final String msg,
			final SimpleAlertNotificationCallback callback) {

		AlertDialog.Builder builder = new AlertDialog.Builder(
				AndroidApplicationContext.getInstance().getApplicationContext());
		builder.setTitle(title);
		builder.setMessage(msg);
		builder.setCancelable(true);
		builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (callback != null) {
					callback.onOk();
				}
			}
		});
		return builder.show();

	}

	@Override
	public void showInputTextDialog(String title, String msg, String content,
			final InputTextDialogCallback callback) {
		final AlertDialog.Builder alert = new AlertDialog.Builder(
				AndroidApplicationContext.getInstance().getApplicationContext());
		final EditText input = new EditText(AndroidApplicationContext
				.getInstance().getApplicationContext());
		input.setFilters(new InputFilter[] { new InputFilter.AllCaps() });
		input.setText("TEST");
		alert.setView(input);
		alert.setTitle(title);
		alert.setMessage(msg);
		input.setText(content);
		alert.setCancelable(true);
		alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String value = input.getText().toString().trim();
				if (callback != null) {
					callback.onPositivie("OK", value);
				}

			}
		});

		alert.setNegativeButton("Annulla",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
					}
				});
		alert.show();

	}

	@Override
	public void showInputTextDialog(String title, String msg,
			final InputTextDialogCallback callback) {
		final AlertDialog.Builder alert = new AlertDialog.Builder(
				AndroidApplicationContext.getInstance().getApplicationContext());
		final EditText input = new EditText(AndroidApplicationContext
				.getInstance().getApplicationContext());
		alert.setView(input);
		alert.setTitle(title);
		alert.setMessage(msg);
		alert.setCancelable(true);
		alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String value = input.getText().toString().trim();
				if (callback != null) {
					callback.onPositivie("OK", value);
				}

			}
		});

		alert.setNegativeButton("Annulla",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
					}
				});
		alert.show();

	}

	public void showTimePickerDialog(String title,
			final InputTextDialogCallback callback) {
		OnTimeSetListener listener = new OnTimeSetListener() {

			@Override
			public void onTimeSet(TimePicker arg0, int hour, int min) {
				if (callback != null) {
					String hourStr = String.valueOf(hour);
					hourStr = String.format("%02d", hour);

					String minuteStr = String.valueOf(min);
					minuteStr = String.format("%02d", min);
					callback.onPositivie("OK", hourStr + ":" + minuteStr);
				}

			}
		};

		Calendar cal = (Calendar) AndroidModelContainer.getInstance().getModel(
				"CURRENT_TIME");
		final TimePickerDialog dialog = new TimePickerDialog(
				AndroidApplicationContext.getInstance().getApplicationContext(),
				listener, cal.getTime().getHours(), cal.getTime().getMinutes(),
				true);

		dialog.setButton("OK", dialog);

		dialog.setButton2("CANCELLA", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				dialog.dismiss();

			}
		});
		dialog.setTitle(title);
		dialog.show();

	}

	// public void showNumberPickerDialog(String title,
	// final InputTextDialogCallback callback) {
	// NumberPicker picker = new NumberPicker(AndroidApplicationContext
	// .getInstance().getApplicationContext());
	// Dialog d = createCustomDialog(title, picker);
	// d.show();
	// }

	public void showDatePickerDialog(String title,
			final InputDateDialogCallback callback) {
		OnDateSetListener listener = new OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker arg0, int year, int month, int day) {
				if (callback != null) {
					String dayStr = String.valueOf(day);
					dayStr = dayStr.length() == 2 ? dayStr : "0" + dayStr;

					String monthStr = String.valueOf(month + 1);
					monthStr = monthStr.length() == 2 ? monthStr : "0"
							+ monthStr;
					callback.onPositivie("OK", dayStr + "/" + monthStr + "/"
							+ year);
				}

			}
		};

		int iDay, iMonth, iYear;
		Calendar cal = (Calendar) AndroidModelContainer.getInstance().getModel(
				"CURRENT_TIME");
		iDay = cal.get(Calendar.DAY_OF_MONTH);
		iMonth = cal.get(Calendar.MONTH);
		iYear = cal.get(Calendar.YEAR);

		final DatePickerDialog dialog = new DatePickerDialog(
				AndroidApplicationContext.getInstance().getApplicationContext(),
				listener, iYear, iMonth, iDay);

		dialog.setButton("OK", dialog);
		dialog.updateDate(iYear, iMonth, iDay);

		dialog.getDatePicker().setCalendarViewShown(false);
		dialog.setButton2("CANCELLA", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				dialog.dismiss();

			}
		});
		dialog.setTitle(title);
		dialog.show();

	}

	public void showDatePickerDialog(String title,
			final InputDateDialogCallback callback, int iYear, int iMonth,
			int iDay) {
		OnDateSetListener listener = new OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker arg0, int year, int month, int day) {
				if (callback != null) {
					String dayStr = String.valueOf(day);
					dayStr = dayStr.length() == 2 ? dayStr : "0" + dayStr;

					String monthStr = String.valueOf(month + 1);
					monthStr = monthStr.length() == 2 ? monthStr : "0"
							+ monthStr;
					callback.onPositivie("OK", dayStr + "/" + monthStr + "/"
							+ year);
				}

			}
		};

		final DatePickerDialog dialog = new DatePickerDialog(
				AndroidApplicationContext.getInstance().getApplicationContext(),
				listener, iYear, iMonth, iDay);

		dialog.setButton("OK", dialog);
		dialog.updateDate(iYear, iMonth - 1, iDay);

		dialog.getDatePicker().setCalendarViewShown(false);
		dialog.setButton2("CANCELLA", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				dialog.dismiss();

			}
		});
		dialog.setTitle(title);
		dialog.show();

	}

	@SuppressWarnings("unchecked")
	@Override
	public <E> E createCustomDialog(String title, String content,
			int textViewId, int contentViewId, int okResourceId,
			final SimpleAlertNotificationCallback callback) {
		Context mContext = AndroidApplicationContext.getInstance()
				.getApplicationContext();
		Dialog dialog = new Dialog(mContext);
		dialog.setContentView(contentViewId);

		TextView textView = null;
		textView = (TextView) dialog.findViewById(textViewId);

		if (textView != null) {
			textView.setText(content);
		}

		if (!StringUtils.isEmpty(title)) {
			dialog.setTitle(title);
		}
		Button button = null;
		try {
			button = (Button) dialog.findViewById(okResourceId);
		} catch (ClassCastException c) {
			throw new RuntimeException(
					"Passed id from resource is not a Button!! Are you sure your dialog contains a confirm Button?");
		}

		if (callback != null) {
			button.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					callback.onOk();
				}
			});
		}

		return (E) dialog;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <E> E createCustomDialog(String title, int contentViewId,
			int okResourceId, final SimpleAlertNotificationCallback callback) {
		Context mContext = AndroidApplicationContext.getInstance()
				.getApplicationContext();
		Dialog dialog = new Dialog(mContext);
		dialog.setContentView(contentViewId);

		if (!StringUtils.isEmpty(title)) {
			dialog.setTitle(title);
		}
		Button button = null;
		try {
			button = (Button) dialog.findViewById(okResourceId);
		} catch (ClassCastException c) {
			throw new RuntimeException(
					"Passed id from resource is not a Button!! Are you sure your dialog contains a confirm Button?");
		}

		if (callback != null) {
			button.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					callback.onOk();
				}
			});
		}

		return (E) dialog;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <E, T> E createCustomDialog(String title, int contentView,
			DialogCallback<T> callback) {
		Context mContext = AndroidApplicationContext.getInstance()
				.getApplicationContext();
		Dialog dialog = new Dialog(mContext);
		dialog.setContentView(contentView);

		if (!StringUtils.isEmpty(title)) {
			dialog.setTitle(title);
		}
		// TODO finire di implementare per usare la callback
		return (E) dialog;
	}

	@Override
	public Dialog createCustomDialog(String title, View content) {
		Context mContext = AndroidApplicationContext.getInstance()
				.getApplicationContext();
		Dialog dialog = new Dialog(mContext);
		dialog.setCancelable(true);
		dialog.setContentView(content);
		dialog.setTitle(title);
		return dialog;
	}

	@Override
	public void showOptionDialog(String title, String msg,
			final String[] items, final InputTextDialogCallback callback) {
		BasicLogger.writeLog("AndroidNotification", "showSpinnerDialog");

		AlertDialog.Builder builder = new AlertDialog.Builder(
				AndroidApplicationContext.getInstance().getApplicationContext());
		builder.setTitle(title);
		builder.setSingleChoiceItems(items, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						callback.onPositivie("OK", items[item]);
						dialog.dismiss();
					}
				});

		builder.setNegativeButton("Annulla",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
					}
				});
		AlertDialog alert = builder.create();
		alert.setCancelable(true);
		alert.show();
	}

	public void showNumberPickerDialog(String title, String msg,
			View numberPickerView, int pickerId, int layoutid, int[] btId,
			int initialValue, final int offset,
			final InputTextDialogCallback callback) {

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				AndroidApplicationContext.getInstance().getApplicationContext());
		builder.setTitle(title);
		builder.setMessage(msg);
		if (numberPickerView.getParent() == null) {
			builder.setView(numberPickerView);
		} else {
			numberPickerView = null;
			numberPickerView = it.eng.area118.mdocommon.android.util.ViewUtils
					.inflate(AndroidApplicationContext.getInstance()
							.getApplicationContext(), layoutid);

			builder.setView(numberPickerView);
		}

		final NumberPicker picker = (NumberPicker) numberPickerView
				.findViewById(pickerId);
		picker.setMinValue(0);
		picker.setMaxValue(10000);
		picker.setValue(initialValue);
		picker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

		if (numberPickerView != null) {
			Button advance = (Button) numberPickerView.findViewById(btId[0]);
			if (advance != null) {
				advance.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						picker.setValue((picker.getValue() + offset)
								% picker.getMaxValue());
					}
				});
			}
			Button minus = (Button) numberPickerView.findViewById(btId[1]);
			if (minus != null) {
				minus.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						picker.setValue((picker.getValue() - offset)
								% picker.getMaxValue());
					}
				});
			}

		}

		// builder.setSingleChoiceItems(items, -1,
		// new DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog, int item) {
		// callback.onPositivie("OK", items[item]);
		// dialog.dismiss();
		// }
		// });
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				int value = picker.getValue();
				dialog.dismiss();
				dialog.cancel();
				builder.setView(null);
				if (callback != null) {
					callback.onDataReceived(String.valueOf(value));
				}

			}
		});
		builder.setNegativeButton("Annulla",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						if (callback != null) {
							callback.onDataReceived(String.valueOf(0));
						}
						dialog.dismiss();
						dialog.cancel();
						builder.setView(null);

					}
				});
		// builder.setItems(items, new DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog, int item) {
		// Toast.makeText(
		// AndroidApplicationContext.getInstance()
		// .getApplicationContext(), items[item],
		// Toast.LENGTH_SHORT).show();
		// }
		// });
		AlertDialog alert = builder.create();
		alert.setCancelable(true);
		alert.show();
	}

	@Override
	public void showSpinnerDialog(String title, String msg,
			final String[] items, final InputTextDialogCallback callback) {

		AlertDialog.Builder builder = new AlertDialog.Builder(
				AndroidApplicationContext.getInstance().getApplicationContext());
		builder.setTitle(title);
		builder.setSingleChoiceItems(items, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						callback.onPositivie("OK", items[item]);
						dialog.dismiss();
					}
				});

		builder.setNegativeButton("Annulla",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
					}
				});
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				Toast.makeText(
						AndroidApplicationContext.getInstance()
								.getApplicationContext(), items[item],
						Toast.LENGTH_SHORT).show();
			}
		});
		AlertDialog alert = builder.create();
		alert.setCancelable(true);
		alert.show();
	}

}
